package control;

import java.io.IOException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.Util;

import dao.UserData;

/**
 * Servlet implementation class ForgotPassword
 */
public class ForgotPassword extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ForgotPassword() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String email = request.getParameter("email");
		String email_err = "";
		UserData ud = new UserData();
		boolean checkEmail = ud.checkEmail(email);
		email = email.trim();
		if (email.equals("")) {
			email_err += "bạn chưa nhập email";
		} else {
			Pattern patternObject = Pattern
					.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
			Matcher matcherObject = patternObject.matcher(email);
			if (!matcherObject.matches()) {
				email_err += "bạn nhập email không hợp lệ";
			} else {
				if (!checkEmail) {
					email_err += "Bạn Nhập email không đúng";
				}
			}

		}

		String url = "/forgetCongra.jsp";
		request.setAttribute("email", email);
		if (checkEmail && email_err.length()==0 ) {
			String randomchuoi = "ZXCVBNMLKJHGFDSAQWERTYUIOP";
			String ketqua = "";
			try {
				
			Random random = new Random();
			for (int i = 0; i < 12; i++) {
				int temp = random.nextInt(randomchuoi.length());
				ketqua += randomchuoi.charAt(temp);
			}
			} catch (Exception e) {
				response.sendRedirect("forgetPass.jsp");
			}
			String body = "Chào Mừng bạn đến với Game Đai chiến Thiên Sơn Bạn Vừa Đổi mật thành công tài khoản tại trang game thiên Sơn, Mật Khẩu của bạn là : "
					+ ketqua;
			ud.updatePass(body, email);
			try {
				Util.sendMail(email, body);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		if (email_err.length() > 0 ) {
			url = "/forgetPass.jsp";
			request.setAttribute("email_err", email_err);

		}
		RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
		rd.forward(request, response);
	}

}
